﻿using System;
using System.Linq;
using System.Web;
using EasySite.Infrastructure.Extensions;
using EasySite.Infrastructure.Security;
using EasySite.Models;
using EasySite.Models.Enums;

namespace EasySite.Services.Implementations
{
    public class UserService : ServiceBase, IUserService
    {
        private const string EncryptKey = "EasySiteMD5Key2011";

        #region Implementation of IUserService

        public User GetUser(string username)
        {
            var query = from u in DataContext.Users
                        where u.Username == username && u.Deleted == false && u.Activated
                        select u;
            var user = query.FirstOrDefault();
            if (user != null)
            {
                user.DecodedPassword = CryptoService.MD5Decrypt(user.Password, EncryptKey);
            }
            return user;
        }

        public CreateUserStatus CreateUser(User user)
        {
            var existingUser = DataContext.Users.FirstOrDefault(u => u.Username == user.Username || u.Email == user.Email);
            if (existingUser != null)
            {
                if (existingUser.Username.Eq(user.Username))
                {
                    return CreateUserStatus.UsernameExists;
                }
                return CreateUserStatus.EmailExists;
            }
            user.CreatedDate = DateTime.Now;
            user.Password = CryptoService.MD5Encrypt(user.DecodedPassword, EncryptKey);
            DataContext.Users.Add(user);
            var success = base.TrySaveChanges();
            return success ? CreateUserStatus.Success : CreateUserStatus.Failed;
        }

        public bool Login(string username, string password, string ip)
        {
            var user = GetUser(username);
            if (user == null)
            {
                return false;
            }
            var success = password == user.DecodedPassword;
            if (success)
            {
                user.LoginCount += 1;
                user.LastLogin = DateTime.Now;
                user.LastLoginIP = ip;
                base.TrySaveChanges();
            }
            return success;
        }

        public string[] GetRoles(string username)
        {
            var query = from a in DataContext.UserInRoles
                        where a.User.Username == username
                        select a.Role.Name;
            return query.ToArray();
        }

        #endregion
    }
}
